package bootstrap

import (
	"bytes"
	"encoding/json"
	"go.getaway.adminspro.padmins.com/untils"
	"go.getaway.adminspro.padmins.com/untils/handler"
)

func Permission(c *handler.Handler) (map[string]interface{}, untils.Error) {
	token := ""
	resource := c.Request.Params("method").(string)
	routersPermission := c.Di.Get("routersPermission").(map[string]string)
	permission := routersPermission[resource]
	token = c.Request.Header("Access-Token")
	if token == "" {
		token = c.Request.Header("Authorization")
	}

	if token == "" {
		token = c.Request.Cookie("token")
	}

	if token == "" {
		token = c.Request.Params("token", "").(string)
	}

	if c.Auth.Init(token) == false {
		if permission == "public" {
			return nil, nil
		}
		return nil, untils.NewBusinessError(20001, "登录状态失效")
	}

	if c.Auth.Get("status").(int64) != 1 {
		return nil, untils.BusinessErrorf("账号已禁用")
	}

	if permission == "allow" || permission == "public" {
		c.Auth.SetAllowResources([]interface{}{
			resource,
		})
	}

	if c.Auth.Permission(resource) == false {
		return nil, untils.BusinessErrorf("没有权限操作")
	}

	if c.Request.Method() == "POST" {
		content := bytes.NewBuffer([]byte{})
		jsonEncoder := json.NewEncoder(content)
		jsonEncoder.SetEscapeHTML(false)
		_ = jsonEncoder.Encode(c.Request.Params())
		e := c.Auth.Log(map[string]interface{}{
			"admin_id":    c.Auth.Get("id"),
			"username":    c.Auth.Get("username"),
			"url":         untils.MbSubStr(c.Request.Header("Referer"), 0, 255),
			"title":       untils.MbSubStr(resource, 0, 255),
			"content":     content.String(),
			"ip":          c.Request.Ip(),
			"useragent":   untils.MbSubStr(c.Request.Header("User-Agent"), 0, 1000),
			"create_time": untils.Date("Y-m-d H:i:s"),
		})

		if e != nil {
			return nil, untils.BusinessErrorf(e.Error())
		}
	}

	return nil, nil
}
